package me.bemayor.components.twin.items;

import me.bemayor.BeMayor;
import me.bemayor.api.customgui.GuiButton;
import me.bemayor.api.customgui.WorkbenchGui;
import me.bemayor.components.twin.TwinUsage;
import org.bukkit.*;
import org.bukkit.block.Chest;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.ItemStack;

import java.util.ArrayList;
import java.util.Arrays;

public class TwinMakerGui {

    private Location chestLocation;
    private final WorkbenchGui myGui;

    public TwinMakerGui() {

        myGui = new WorkbenchGui(ChatColor.DARK_RED + "孪生制造机", 2, 1, 1);

        myGui.setButton(new GuiButton("§6✦ 便携孪生箱合成 ✦", Material.ANVIL, this::clickButtons));

        myGui.setDescription(
                "§6[孪生制造机] 将§b末影之眼、陷阱箱§d合成便携孪生箱§d\n" +
                        "     使用方法：\n" +
                        "        1.将§b末影之眼、陷阱箱§d放在左侧的红色栏位；\n" +
                        "        2.单击合成按钮进行合成；\n" +
                        "        3.关闭界面时合成的便携孪生箱会自动进入背包。"
        );

        myGui.setCloseText("");
        myGui.setGuiCloseAction(event -> {
            Player p = (Player) event.getPlayer();
            p.playSound(p.getEyeLocation(), Sound.BLOCK_SHULKER_BOX_CLOSE, 1F, 1F);
        });

        myGui.addRecipeItem(Material.ENDER_EYE);
        myGui.addRecipeItem(Material.TRAPPED_CHEST);
    }

    public void open(Player player, Location chestLocation) {
        if (chestLocation != null) {
            this.chestLocation = chestLocation;
            myGui.open(player);
        } else {
            player.sendMessage("§6[孪生制造机] §c孪生制造机没有放置在箱子的背面！");
        }
    }

    private void clickButtons(InventoryClickEvent event) {
        Player player = (Player) event.getWhoClicked();
        ArrayList<String> ConfirmLore;
        if (myGui.checkInputItem()) {
            ItemStack outcome = BeMayor.getApiManager().getCustomItemManager().getTemplateById("PORTABLE_TWIN_BOX").getCloneItemStack();
            TwinUsage.setLocationToItem(outcome, TwinUsage.getStringFromLocation(chestLocation));
            TwinUsage.setNameToItem(outcome, TwinUsage.getChest(chestLocation).getCustomName());
            myGui.setInputToOutput(outcome, player);
            ConfirmLore = new ArrayList<>(Arrays.asList(
                    "=========",
                    "§f便携孪生箱已合成完成"
            ));
            player.playSound(player.getEyeLocation(), Sound.ITEM_BOOK_PUT, 1F, 1F);
        } else {
            ConfirmLore = new ArrayList<>(Arrays.asList(
                    "=========",
                    "§f请将§b末影之眼§d和§b陷阱箱§d放入左侧"
            ));
            player.sendMessage("§6[孪生制造机] §d请将§b末影之眼§d和§b陷阱箱§d放入左侧的红色栏位。");
        }
        myGui.getButtons().get(0).setLore(ConfirmLore);
        myGui.refreshButton(0);
        event.setCancelled(true);
    }
}
